package org.jash.shop2201.shop

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.jash.shop2201.entity.BannerEntity
import org.jash.shop2201.entity.Category
import org.jash.shop2201.entity.Goods
import org.jash.shop2201.mvvm.BaseViewModel
import org.jash.shop2201.net.service

class CategoryViewModel : BaseViewModel() {
    val goodsLiveData by lazy { MutableLiveData<List<Goods>>() }
    val categoryLiveData by lazy { MutableLiveData<List<Category>>() }
    fun loadGoods(cid: Int, page: Int, size: Int) {
        viewModelScope.launch {
            try {
                val res = service.getGoods(cid, page, size)
                if (res.code == 200) {
                    goodsLiveData.postValue(res.data)
                } else {
                    errorLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e: Exception) {
                errorLiveData.postValue(e)
            }
        }
    }

    fun loadCategory() {
        viewModelScope.launch {
            try {
                val res = service.getCategory()
                if (res.code == 200) {
                    categoryLiveData.postValue(res.data)
                } else {
                    errorLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e: Exception) {
                errorLiveData.postValue(e)
            }
        }
    }

}